﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using System.Drawing.Imaging;
using System.Drawing.Imaging.Depend;
using System.Drawing.Imaging.Assist;

namespace System.Drawing.Imaging.Image
{
    public static class ImageExtensions
    {
        /// <summary>
        /// Get Image Thumbnail
        /// </summary>
        /// <param name="bitmap">Orgingal image</param>
        /// <param name="size">Thumbnail Size</param>
        /// <param name="bgcolor">Background color</param>
        /// <returns>Bitmap</returns>
        public static Bitmap GetThumbnailImage(this Bitmap bitmap, Size size,Color bgcolor)
        {
            if (bitmap.IsNull())
                throw new NullReferenceException();

            //Thumbnail calculation factor
            double ThumbnailFactor = Math.Min((double)size.Height / (double)bitmap.Height ,(double)size.Width / (double)bitmap.Width);

            System.Drawing.Bitmap returnimage = new System.Drawing.Bitmap(size.Width, size.Height);

            //Drawing Thumbnail
            using (System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(returnimage))
            {
                //Draw background
                g.Clear(bgcolor);

                g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
                g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;

                //Turn drawing as
                g.DrawImage(bitmap, new System.Drawing.Rectangle(0, 0, 
                    (int)(bitmap.Width * ThumbnailFactor), (int)(bitmap.Height * ThumbnailFactor)), 
                    new System.Drawing.Rectangle(0, 0, bitmap.Width, bitmap.Height), System.Drawing.GraphicsUnit.Pixel);
            }

            return returnimage;
        }

        /// <summary>
        /// Get Image Thumbnail
        /// </summary>
        /// <param name="bitmap">Orgingal image</param>
        /// <param name="size">Thumbnail Size</param>
        /// <param name="bgcolor">Background color</param>
        /// <returns>Bitmap</returns>
        public static Bitmap GetThumbnailImage(this Bitmap bitmap,int width,int height, Color bgcolor)
        {
            return GetThumbnailImage(bitmap, new Size(width, height), bgcolor);
        }

        /// <summary>
        /// Image processing
        /// </summary>
        /// <param name="image">source</param>
        /// <param name="type">type</param>
        /// <returns>image</returns>
        public static Bitmap ProcessorImage(this Bitmap image, ImageColorType type)
        {
            if (image.IsNull())
                throw new NullReferenceException();

            //Create Clone Object
            Bitmap temp_image = (Bitmap)image.Clone();

            return ImageProcessFactory.GetProcessor(type, temp_image).ProcessImage();
        }
    }
}
